package com.cloudfun.campusshare.service.impl;

import com.cloudfun.campusshare.device.protocol.command.Frame;
import com.cloudfun.campusshare.device.protocol.command.PumpFrame;
import com.cloudfun.campusshare.entity.DeviceEntity;
import com.cloudfun.campusshare.entity.ResponseMessageEntity;
import com.cloudfun.campusshare.repo.DeviceEntityRepo;
import com.cloudfun.campusshare.repo.ResponseMessageRepo;
import com.cloudfun.campusshare.service.ResponseMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * Created by Huqin on 2020/2/10
 */
@Service
public class ResponseMessageServiceImpl implements ResponseMessageService {

    @Autowired
    private ResponseMessageRepo responseMessageRepo;

    @Autowired
    private DeviceEntityRepo deviceEntityRepo;

    @Override
    public boolean create(String messageId, String deviceType, String imei, Frame frame) {
        return buildRecord(messageId,deviceType,imei,frame.toString(),frame.additionalCheckSumStr());
    }

    @Override
    public boolean create(String messageId, String deviceType, String imei, PumpFrame frame) {
        return buildRecord(messageId,deviceType,imei,frame.toString(),frame.getCheckSum());
    }

    private boolean buildRecord(String messageId, String deviceType, String imei, String content,String checkSum) {
        Optional<ResponseMessageEntity> entityByIdOpt = responseMessageRepo.findById(messageId);
        // 已经有这个消息，说明处理过了不需要处理
        if (entityByIdOpt.isPresent()) {
            return false;
        }
        DeviceEntity deviceEntity = deviceEntityRepo.findByImei(imei);
        if (null == deviceEntity) {
            return false;
        }
        ResponseMessageEntity entity = ResponseMessageEntity.builder()
                .id(messageId)
                .deviceType(deviceType)
                .deviceId(deviceEntity.getId())
                .content(content)
                .checksum(checkSum)
                .build();
        responseMessageRepo.save(entity);
        return true;
    }
}
